const XlsxPopulate = require('xlsx-populate');

function getWorkbook() {
    return XlsxPopulate.fromBlankAsync();
}

function generate(sheetData) {

    return getWorkbook()
        .then(function (workbook) {
            workbook.sheet(0).cell("A1").value([
                [1, 2, 3],
                [4, 5, 6],
                [7, 8, 9]
            ]).style("fontColor", "ff0000");
            return workbook.outputAsync();
        });
}

export default (sheetData, wbname) => {
    wbname = wbname || 'Workbook';
    return generate(sheetData)
            .then(function (blob) {
                if (window.navigator && window.navigator.msSaveOrOpenBlob) {
                    window.navigator.msSaveOrOpenBlob(blob, wbname + ".xlsx");
                } else {
                    var url = window.URL.createObjectURL(blob);
                    var a = document.createElement("a");
                    document.body.appendChild(a);
                    a.href = url;
                    a.download = wbname + ".xlsx";
                    a.click();
                    window.URL.revokeObjectURL(url);
                    document.body.removeChild(a);
                }
            })
            .catch(function (err) {
                console.error(err.message || err);
                throw err;
            });
}
